package com.gzhryc.shared_device.oem.h5.agent.jetty;

import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;

import javax.servlet.DispatcherType;
import java.util.EnumSet;

/**
 * Jetty服务
 *
 * @author zhanghao
 */
public class JettyHttpServer {

    final static Logger log = Logger.getLogger(JettyHttpServer.class);

    public static void start(String configPath) throws Exception {
        Server server = new Server();
        
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(PropertyTools.get().getInt(WebConstants.PROGRAM_TYPE + ".Jetty.port"));
        connector.setIdleTimeout(90000L);
        server.setConnectors(new Connector[]{connector});

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(MainServlet.class, "/*");

        String webapp = PropertyTools.get().getString(WebConstants.PROGRAM_TYPE + ".webapp");
        context.setBaseResource(Resource.newResource(webapp));

        context.addFilter(CommonFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        context.addFilter(AjaxSecurityFilter.class, "*.do", EnumSet.of(DispatcherType.REQUEST));
        context.addFilter(AjaxSecurityFilter.class, "*.data", EnumSet.of(DispatcherType.REQUEST));

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[]{context, new DefaultHandler()});
        server.setHandler(handlers);

        log.info("*************** HTTP服务启动，端口：" + connector.getPort() + " ******************");

        server.start();
        server.join();
    }
}
